/**
 * 花滩子水库环境监测大屏主程序 
 * 功能包含：地图初始化、数据可视化、动态交互、实时更新 
 */

// 全局配置对象 
const CONFIG = {
    mapCenter: [27.72545, 108.21235], // 水库地理坐标 
    zoomLevel: 14,                   // 地图初始缩放级别 
    dataUpdateInterval: 300000,      // 数据更新间隔（5分钟）
    scrollSpeed: 40,                 // 文本滚动速度（毫秒/像素）
    apiEndpoints: {
        weather: 'https://api.caiyunapp.com/v2.6/ 你的密钥/经度,纬度/weather'
    }
};

// 初始化地图 
function initMap() {
    const map = L.map('map-layer', {
        center: CONFIG.mapCenter, // 地图中心坐标
        zoom: CONFIG.zoomLevel, // 初始缩放级别
        // zoomControl: false, // 禁用默认缩放控件
        attributionControl: false, // 禁用右下角默认属性控件
        // preferCanvas: true  // 优化大量标记性能 
    });

    // 确保地图容器层级设置
    document.querySelector('.map-renderer').style.zIndex = 1;

    var baseLayers = {
        "矢量底图": L.tileLayer(
            'http://t{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=a5061c247722768b346612e137d0ada5',
            {
                // attribution: '天地图',
                maxNativeZoom: 18,
                maxZoom: 100,
                minZoom: 5,
                subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
            }),
        "影像底图": L.tileLayer(
            'http://t{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=a5061c247722768b346612e137d0ada5',
            {
                attribution: '天地图',
                maxNativeZoom: 18,
                maxZoom: 100,
                minZoom: 5,
                subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
            }),
        "地形晕渲": L.tileLayer(
            'http://t{s}.tianditu.gov.cn/ter_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=a5061c247722768b346612e137d0ada5',
            {
                // attribution: '天地图',
                maxNativeZoom: 18,
                maxZoom: 100,
                minZoom: 5,
                subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
            }),
    };

    baseLayers["影像底图"].addTo(map);

    var overlays = {
        "矢量注记": L.tileLayer(
            'http://t{s}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=a5061c247722768b346612e137d0ada5',
            {
                // attribution: '天地图',
                maxNativeZoom: 18,
                maxZoom: 100,
                minZoom: 5,
                subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
            }),
        "影像注记": L.tileLayer(
            'http://t{s}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=a5061c247722768b346612e137d0ada5',
            {
                // attribution: '天地图',
                maxNativeZoom: 18,
                maxZoom: 100,
                minZoom: 5,
                subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
            }),
        "地形注记": L.tileLayer(
            'http://t{s}.tianditu.gov.cn/cta_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cta&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=a5061c247722768b346612e137d0ada5',
            {
                // attribution: '天地图',
                maxNativeZoom: 18,
                maxZoom: 100,
                minZoom: 5,
                subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
            }),
        "全球境界": L.tileLayer(
            'http://t{s}.tianditu.gov.cn/ibo_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ibo&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=a5061c247722768b346612e137d0ada5',
            {
                // attribution: '天地图',
                maxNativeZoom: 18,
                maxZoom: 100,
                minZoom: 5,
                subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
            }),
    };

    overlays["影像注记"].addTo(map);

    L.control.layers(baseLayers, overlays).addTo(map);

    // 自定义功能按钮控件
    const CustomControl = L.Control.extend({
        options: { position: 'topright' }, // 控件位置

        onAdd: function (map) {
            // 创建控件容器
            const container = L.DomUtil.create('div', 'custom-control');

            // 主按钮
            this.mainButton = this._createButton('<i class="fas fa-bars"></i>', '菜单', () => {
                L.DomUtil.toggleClass(this.menu, 'active'); // 切换菜单显示状态
            });
            container.appendChild(this.mainButton); // 添加到容器

            // 功能菜单
            this.menu = this._createMenu([
                { icon: 'fa-ruler', text: '测量工具', action: () => alert('测量功能') },
                { icon: 'fa-download', text: '导出数据', action: () => alert('导出功能') },
                { icon: 'fa-filter', text: '数据筛选', action: () => alert('筛选功能') },
                { icon: 'fa-layer-group', text: '图层管理', action: () => alert('图层管理') },
                { icon: 'fa-info-circle', text: '图例说明', action: () => alert('图例显示') }
            ]);
            container.appendChild(this.menu);

            // 防止地图点击事件冒泡
            L.DomEvent.disableClickPropagation(container);
            return container;
        },

        _createButton: function (icon, title, handler) {
            const btn = L.DomUtil.create('button');
            btn.innerHTML = icon;
            btn.title = title;
            btn.style.cssText = 'width:30px; height:30px; margin:2px;';
            L.DomEvent.on(btn, 'click', handler);
            return btn;
        },

        _createMenu: function (items) {
            const menu = L.DomUtil.create('div', 'function-buttons');
            items.forEach(item => {
                const btn = this._createButton(
                    `<i class="fas ${item.icon}"></i>  ${item.text}`,
                    item.text,
                    item.action
                );
                btn.style.width = '150px';
                btn.style.justifyContent = 'flex-start';
                menu.appendChild(btn);
            });
            return menu;
        }
    });

    // 添加控件到地图
    map.addControl(new CustomControl());

    // 自定义标记点图标
    function createMarkerIcon(color) {
        return L.icon({
            iconUrl: 'images/marker-icon.png', // 替换为你的图标路径
            iconSize: [25, 41], // 图标大小
            iconAnchor: [12, 41], // 图标锚点
            popupAnchor: [1, -34], // 弹出窗口锚点
            // shadowUrl: 'path/to/your/marker-shadow.png', // 替换为你的阴影图标路径
            shadowSize: [41, 41], // 阴影大小
            shadowAnchor: [12, 41], // 阴影锚点
            className: 'marker-icon-' + color // 添加一个类名以便于通过 CSS 控制颜色
        });
    }

    // 添加标记点
    var marker = L.marker([27.72545, 108.21235], {
        icon: createMarkerIcon('red') // 初始颜色为红色
    }).addTo(map);

    // 添加静态标记
    // var markerIocn = L.icon({
    //     iconUrl: 'images/marker-icon.png',
    //     // iconSize: [50, 50],
    // });

    // 给地图添加点击事件
    map.on('click', function (e) {
        // 经纬度坐标。
        var latlng = e.latlng;
        // 设置地图的坐标，添加标记。
        L.marker(latlng, { icon: markerIocn }).addTo(map);
    });

    // 添加折线
    var latlngs = [
        [27.73545, 108.21335],
        [27.73045, 108.21235],
        [27.72445, 108.21635]
    ];

    var polyline = L.polyline(latlngs, { color: 'red' }).addTo(map);

    // 缩放地图以适应折线
    // map.fitBounds(polyline.getBounds());

    // 创建多边形
    var polygon = L.polygon([
        [27.71545, 108.21235],
        [27.71545, 108.22335],
        [27.72245, 108.21335]
    ]).addTo(map);

    // 创建面
    var circle = L.circle([27.72545, 108.20235], {
        color: 'blue',
        fillColor: 'blue',
        fillOpacity: 0.5,
        radius: 500
    }).addTo(map);

    // 添加弹出窗口
    marker.bindPopup("<b>环境监测点位</b>"); //后面添加.openPopup()可默认打开状态
    polyline.bindPopup("<b>工程线路布置</b>");
    polygon.bindPopup("<b>生产生活区</b>");
    circle.bindPopup("<b>我是一个圆形</b>");

    return map;
}

// 初始化ECharts图表 
function initECharts() {
    const charts = {
        water: initWaterChart(),
        air: initAirChart(),
        noise: initNoiseChart()
    };

    // 窗口尺寸变化监听 
    window.addEventListener('resize', () => {
        Object.values(charts).forEach(chart => chart.resize());
    });

    return charts;
}

// 水环境监测折线图 
function initWaterChart() {
    const chart = echarts.init(document.getElementById('water-chart'));

    fetch('data/water.csv')
        .then(response => response.text())
        .then(csvData => {
            const data = parseCSV(csvData);
            const colors = ['#5470C6', '#91CC75'];
            const option = {
                color: colors,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    }
                },
                grid: {
                    right: '20%',
                    left: '5%',
                    bottom: '10%',
                    top: '20%',
                },
                legend: {
                    data: ['COD', 'NH3-N'],
                    textStyle: {
                        color: '#fff'
                    }
                },
                xAxis: [
                    {
                        type: 'category',
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#fff'
                            }
                        },
                        // prettier-ignore
                        data: ['Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep']
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: 'COD',
                        position: 'lfet',
                        alignTicks: true,
                        axisLine: {
                            show: true,
                            lineStyle: {
                                color: colors[0]
                            }
                        },
                        axisLabel: {
                            formatter: '{value} ml'
                        }
                    },
                    {
                        type: 'value',
                        name: 'NH3-N',
                        position: 'right',
                        alignTicks: true,
                        offset: 80,
                        axisLine: {
                            show: true,
                            lineStyle: {
                                color: colors[1]
                            }
                        },
                        axisLabel: {
                            formatter: '{value} ml'
                        }
                    },
                ],
                series: [
                    {
                        name: 'COD',
                        type: 'line',
                        data: [
                            23.2, 25.6, 76.7, 135.6, 162.2, 32.6
                        ]
                    },
                    {
                        name: 'NH3-N',
                        type: 'line',
                        yAxisIndex: 1,
                        data: [
                            26.4, 28.7, 70.7, 175.6, 182.2, 48.7
                        ]
                    },
                ]
            };
            chart.setOption(option);
        });

    return chart;
}

// 空气质量雷达图
function initAirChart() {
    const chart = echarts.init(document.getElementById('air-chart'));
    fetch('data/air.csv')
        .then(response => response.text())
        .then(csvData => {
            const data = parseCSV(csvData);
            const option = {
                grid: { top: 40, bottom: 30, left: 50, right: 30 },
                tooltip: {
                    trigger: 'item'
                },
                radar: {
                    // shape: 'circle',
                    indicator: [
                        { name: 'PM2.5', max: 650 },
                        { name: 'PM10', max: 1600 },
                        { name: 'SO2', max: 3000 },
                        { name: 'NO2', max: 3800 },
                        { name: 'CO', max: 5200 },
                        { name: 'O3', max: 2500 }
                    ]
                },
                series: [
                    {
                        name: '基本污染物',
                        type: 'radar',
                        data: [
                            {
                                value: [420, 300, 2000, 3500, 5000, 1800],
                                name: '基本污染物'
                            },
                        ]
                    }
                ]
            };
            chart.setOption(option);
        });
    return chart;
}

// 噪声监测柱状图
function initNoiseChart() {
    const chart = echarts.init(document.getElementById('noise-chart'));
    fetch('data/noise.csv')
        .then(response => response.text())
        .then(csvData => {
            const data = parseCSV(csvData);
            const
                option = {
                    color: ["#2f89cf"],
                    tooltip: {
                        trigger: "axis",
                        axisPointer: {
                            // 坐标轴指示器，坐标轴触发有效
                            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
                        }
                    },
                    grid: {
                        left: "0%",
                        top: "10px",
                        right: "0%",
                        bottom: "4%",
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: "category",
                            data: [
                                "坝址",
                                "右岸马路岩",
                                "坨家坝",
                                "某点"
                            ],
                            axisTick: {
                                alignWithLabel: true
                            },
                            axisLabel: {
                                textStyle: {
                                    color: "rgba(255,255,255,.6)",
                                    fontSize: "12"
                                }
                            },
                            axisLine: {
                                show: false
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: "value",
                            axisLabel: {
                                textStyle: {
                                    color: "rgba(255,255,255,.6)",
                                    fontSize: "12"
                                }
                            },
                            axisLine: {
                                lineStyle: {
                                    color: "rgba(255,255,255,.1)"
                                    // width: 1,
                                    // type: "solid"
                                }
                            },
                            splitLine: {
                                lineStyle: {
                                    color: "rgba(255,255,255,.1)"
                                }
                            }
                        }
                    ],
                    series: [
                        {
                            name: "直接访问",
                            type: "bar",
                            barWidth: "35%",
                            data: [200, 300, 300, 900, 1500, 1200, 600],
                            itemStyle: {
                                barBorderRadius: 5
                            }
                        }
                    ]
                };
            chart.setOption(option);
        });
    return chart;
}

// 通用数据解析方法 
function parseCSV(csvString) {
    const lines = csvString.split('\n').filter(line => line.trim());
    const headers = lines.shift().split(',');

    return lines.map(line => {
        const values = line.split(',');
        return headers.reduce((obj, header, index) => {
            obj[header.trim()] = parseFloat(values[index]) || values[index].trim();
            return obj;
        }, {});
    });
}

// 动态文本滚动控制器 
class ScrollController {
    constructor(container, filePath) {
        this.container = container;
        this.content = document.createElement('div');
        this.scrollPos = 0;
        this.isPaused = false;
        this.init(filePath);
    }

    async init(filePath) {
        try {
            const response = await fetch(filePath);
            const text = await response.text();
            this.content.innerHTML = text.split('\n').map(line =>
                `<p class="scroll-item">${line}</p>`
            ).join('');
            this.container.appendChild(this.content);
            this.startScrolling();
            this.addEventListeners();
        } catch (error) {
            console.error(' 文本加载失败:', error);
        }
    }

    startScrolling() {
        this.intervalId = setInterval(() => {
            if (!this.isPaused) {
                const containerHeight = this.container.offsetHeight;
                const contentHeight = this.content.scrollHeight;

                if (contentHeight > containerHeight) {
                    this.scrollPos = (this.scrollPos >= contentHeight) ?
                        0 : this.scrollPos + 1;
                    this.content.style.transform = `translateY(-${this.scrollPos}px)`;
                }
            }
        }, CONFIG.scrollSpeed);
    }

    addEventListeners() {
        this.container.addEventListener('mouseenter', () => this.isPaused = true);
        this.container.addEventListener('mouseleave', () => this.isPaused = false);
    }
}

// 状态栏控制器 
class StatusManager {
    constructor() {
        this.weatherElement = document.getElementById('weather');
        this.dateElement = document.getElementById('current-date');
        this.init();
    }

    init() {
        this.updateDateTime();
        setInterval(() => this.updateDateTime(), 1000);
        this.fetchWeather();
    }

    updateDateTime() {
        const options = {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            weekday: 'long',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        };
        this.dateElement.textContent = new Date().toLocaleDateString('zh-CN', options);
    }

    async fetchWeather() {
        try {
            const response = await fetch(CONFIG.apiEndpoints.weather);
            const data = await response.json();
            const weather = data.result.hourly.description;
            const temp = data.result.temperature;
            this.weatherElement.textContent = `${weather} ${temp}℃`;
        } catch (error) {
            this.weatherElement.textContent = "天气数据获取失败";
        }
    }
}

// 主初始化函数 
document.addEventListener('DOMContentLoaded', () => {
    // 核心模块初始化 
    const map = initMap(); // 地图初始化
    const charts = initECharts(); // 图表初始化
    const statusManager = new StatusManager(); // 状态栏初始化

    // 动态滚动文本初始化 
    document.querySelectorAll('.scroll-box').forEach(box => {
        new ScrollController(box, box.dataset.file);
    });
});

// 工具函数 
function createSeries(name, type, data, field, color) {
    return {
        name,
        type,
        data: data.map(d => d[field]), // 提取数据
        itemStyle: { color },
        lineStyle: { width: 2 },
        smooth: true,
        showSymbol: data.length < 30,  // 数据点多时隐藏标记 
        animationDuration: 2000 // 初始动画时长
    };
}

// 数据更新器 
function setupDataUpdater() {
    setInterval(async () => {
        try {
            const [water, air, noise] = await Promise.all([
                fetch('data/water.csv').then(r => r.text()),
                fetch('data/air.csv').then(r => r.text()),
                fetch('data/noise.csv').then(r => r.text())
            ]);

            charts.water.setOption({ dataset: { source: parseCSV(water) } });
            // 其他图表更新类似...

        } catch (error) {
            console.error(' 数据更新失败:', error);
        }
    }, CONFIG.dataUpdateInterval);
}

// 显示时间
var t = null;
t = setTimeout(time, 1000); //開始运行
function time() {
    clearTimeout(t); //清除定时器
    dt = new Date();
    var y = dt.getFullYear();
    var mt = dt.getMonth() + 1;
    var day = dt.getDate();
    var h = dt.getHours(); //获取时
    var m = dt.getMinutes(); //获取分
    var s = dt.getSeconds(); //获取秒
    document.querySelector(".showTime").innerHTML =
        "当前时间：" +
        y +
        "年" +
        mt +
        "月" +
        day +
        "-" +
        h +
        "时" +
        m +
        "分" +
        s +
        "秒";
    t = setTimeout(time, 1000); //设定定时器，循环运行
}
